<template>
  <div class="my-echart-cloud">
    <span class="title">卡路里热词榜</span>
    <v-chart :option="mychart_cloud" id="mychart_cloud"></v-chart>
  </div>
</template>

<script>
import 'echarts-wordcloud';

export default {
  name: 'my_echarts_cloud',
  data() {
    return {
      data: null,
      maskResource: null,
      mychart_cloud: null
    }
  },
  methods: {
    getData(data, maskResource) {
      this.data = data;
      this.maskResource = maskResource;
      this.chartRenderer();
    },
    /**
     * 获取数据后，渲染词云图
     */
    chartRenderer() {
      var myData = []; //全局变量用于存储的字典结构数据
      var dict = {} //用于统计词频的字典
      for(var name in this.data) {
        //第一层遍历，取到 item: name
        for (var character of this.data[name]['character']) {
          //第二层遍历，取到每个 name 中的 character 属性，是个数组

          //通过字典对各个 character 出现的次数进行统计
          if(dict.hasOwnProperty(character)) { //判断字典中是否已有该词的key
            dict[character]++;
          }else{
            dict[character]=1;
          }
        }
      }

      //将数据处理为词云图表可用的结构 push 到 myData 可以筛选掉频率较低的词；
      for(var i in dict){
        myData.push({"name": i, "value": dict[i]})
      }

      const that = this;
      this.mychart_cloud = {
        tooltip: {},
        series: [{
          type: 'wordCloud',
          gridSize: 1,
          sizeRange: [20, 80],
          textStyle: {
              color: function () {
                  return 'rgb(' + [
                      Math.round(Math.random() * 160),
                      Math.round(Math.random() * 160),
                      Math.round(Math.random() * 160)
                  ].join(',') + ')';
              }
          },
          emphasis: {
              textStyle: {
                  shadowBlur: 10,
                  shadowColor: '#333'
              }
          },
          maskImage: that.maskResource,
          data: myData
        }]
      }
    }
  }
}
</script>

<style scoped>
  .my-echart-cloud {
    width: 100%;
    height: 680px;
    position: absolute;
    top: 200px;
    left: 0;
    background-color: #eee;
    border-top: 12px solid #aaaaaa;
    border-left: 12px solid #706961;
    border-right: 12px solid #706961;
    border-bottom: 12px solid #cccccc;
    z-index: 1;
    box-sizing: border-box;
    box-shadow: 0 20px 30px rgba(80, 80, 80, .5);
  }

  #mychart_cloud {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 10px;
  }

  .title {
    position: absolute;
    top: 10px;
    left: 20px;
    font-size: 24px;
    letter-spacing: 1px;
    color: #333;
  }
</style>
